package com.lizhiyu.flink.monitor;

import com.lizhiyu.flink.model.AccessLogDO;
import com.lizhiyu.flink.model.ResultCount;
import com.lizhiyu.flink.model.TimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * 用于统计 每5秒钟，近1分钟的每个接口的访问量
 * 兜底1分钟，使用侧输出流
 */
public class PvTest {
    public static void main(String[] args) throws Exception {
        //构建执行任务环境以及任务的启动的入口, 存储全局相关的参数
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //java,2022-11-11 09-10-10,15
        DataStream<AccessLogDO> ds =  env.addSource(new AccessLogSource());


        //过滤一些没有的url
        SingleOutputStreamOperator<AccessLogDO> filterDS = ds.filter(new FilterFunction<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return StringUtils.isNotBlank(value.getUrl());
            }
        });

        //指定watermark
        SingleOutputStreamOperator<AccessLogDO> watermarkDS = filterDS.assignTimestampsAndWatermarks(WatermarkStrategy
                //指定允许乱序延迟的最大时间 3 秒
                .<AccessLogDO>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //指定POJO事件时间列，毫秒
                .withTimestampAssigner((event, timestamp) -> event.getCreateTime().getTime()));



        //最后的兜底数据
        OutputTag<AccessLogDO> lateData = new OutputTag<AccessLogDO>("lateDataLog"){};

        //根据访问url进行分组
        KeyedStream<AccessLogDO, String> keyedStream = watermarkDS.keyBy(new KeySelector<AccessLogDO, String>() {
            @Override
            public String getKey(AccessLogDO value) throws Exception {
                return value.getUrl();
            }
        });

        SingleOutputStreamOperator<ResultCount> tenMinPV = keyedStream
                //开窗，滑动窗口，每5秒钟统计近60秒的访问量
                .window(SlidingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(60), Time.seconds(5)))
                //允许1分钟延迟
                .allowedLateness(Time.minutes(1))
                //设置侧输出流
                .sideOutputLateData(lateData)
                //增量聚合，有两个参数，第二个参数为ProcessWindowFunction 这个可以获得窗口上下文信息，增量聚合迭代器中只有一条数据
                .aggregate(new AggregateFunction<AccessLogDO, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    @Override
                    public Long add(AccessLogDO value, Long accumulator) {
                        return accumulator + 1;
                    }
                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                }, new ProcessWindowFunction<Long, ResultCount, String, TimeWindow>() {
                    @Override
                    public void process(String value, Context context, Iterable<Long> elements, Collector<ResultCount> out) throws Exception {
                        ResultCount resultCount = new ResultCount();
                        resultCount.setUrl(value);
                        resultCount.setType("每5秒统计近1分接口PV");
                        resultCount.setStartTime(TimeUtils.format(context.window().getStart()));
                        resultCount.setEndTime(TimeUtils.format(context.window().getEnd()));
                        long total = elements.iterator().next();
                        resultCount.setCount(total);
                        out.collect(resultCount);
                    }
                });

        tenMinPV.print("pv:");
        env.execute();
    }
}
